Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
此題要求判斷數值是否為左右對稱。可透過比對原數值與反轉後的數值是否相等來解。
若要完成Follow up條件,可透過比對其中一半數字是否跟另一半數字對稱來達成。
class Solution:
def isPalindrome(self, x: int) -> bool:
if str(x) == str(x)[::-1]:
return True
else:
return False
Follow up
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or x % 10 == 0 and x != 0:
return False
revertedNumber = 0;
while x > revertedNumber:
revertedNumber = revertedNumber * 10 + x % 10;
x //= 10;
# When the length is an odd number, we can get rid of the middle digit by revertedNumber/10
# For example when the input is 12321, at the end of the while loop we get x = 12, revertedNumber = 123,
# since the middle digit doesn't matter in palidrome(it will always equal to itself), we can simply get rid of it.
return x == revertedNumber or x == revertedNumber//10
希望透過記錄解題的過程,可以對於資料結構及演算法等有更深一層的想法。
如有需訂正的地方歡迎告知,若有更好的解法也歡迎留言,謝謝。